import { LoadPanel } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import CpasLayout from '~/public/cpas-business/cpas-table/CpasLayout';
import BusinessTypeModal from '../../components/search/BusinessTypeModal';
import SearchRenderC from '../../components/search/SearchRenderC';
import { getAccountInfo } from '../YearAnalysis/server';
import { buildCol, tableColumnsData } from '../YearAnalysis/tableColumnsData';
const InventoryAnalysisProductStoreAnalysis: React.FC = (props: any) => {
  const pageType = props?.params?.type;
  let typeUrl = 'get.goods.type';
  let dataUrl = 'Analysis.Inventory.SPCK';

  const cpasNotesRef = useRef<any>(null);
  const searchRenderC = useRef<any>();
  const { initialState } = useModel('@@initialState');
  const businessTypeModal = useRef<any>(null);
  // const yearDateModel: any = useModel('qjModel');
  const ztModel: any = useModel('ztModel');
  const [selectTreeNode, setSelectTreeNode] = useState<any>(null);
  const { ztDates } = ztModel;
  const [treeListData, setTreeListData] = useState<any[]>();
  const { dbname, sjnd } = initialState?.curPart as any;
  const [Transaction_Type, setTransaction_Type] = useState<any[]>(['全部']);
  const [columnsData, setColumnsData] = useState<any[]>([]);
  const [tableData, setTtableData] = useState<any[]>();
  const [Load, setLoad] = useState<any>(false);
  const dataSorce = useRef<any[]>();
  const searchcallback = async () => {
    const q = searchRenderC.current.getFormSearchValues();

    const queryDate = {
      dates: q.dates,
      startYear: q.startYear,
      endYear: Number(q.endYear),
    };
    console.log(1, 'li', queryDate);

    let queyType: any = queryDate;
    if (q.TransactionType !== '全部') {
      queyType = { ...queyType, mainType: q.TransactionType };
    }
    setLoad(true);
    await getProductQuery(queyType);
    setTimeout(() => {
      setLoad(false); // 页面加载时间长
    }, 500);
  };

  const setSummeryCallback = (a: any, e: any) => {
    if (e === '业务类型设置') {
      businessTypeModal.current.show();
    }
  };
  function renderSearch() {
    return (
      <SearchRenderC
        yearDate={null}
        ref={searchRenderC}
        pageType={pageType}
        Transaction_Type={Transaction_Type}
        setSummeryCallback={setSummeryCallback}
      />
    );
  }

  const getProductType = async (a: any) => {
    setLoad(true);
    await getProductQuery(a);

    const dd: any = await getAccountInfo(typeUrl, { dbname: dbname });
    setTimeout(() => {
      setLoad(false); // 页面加载时间长
    }, 500);
    if (dd.data?.length) {
      setTreeListData(
        dd.data.map((a: any) => {
          return {
            ...a,
            typeCode: a.typeCode,
          };
        }),
      );
    }
  };

  const getTransactionType = async () => {
    const dd: any = await getAccountInfo('get.Transaction.type', { dbname: dbname });
    if (dd.data?.length) {
      setTransaction_Type(['全部'].concat(dd.data.map((a: any) => a.mainType)));
    }
  };

  const getProductQuery = async (params: {
    startYear: string;
    endYear: string;
    dates: string[];
    mainType?: string;
  }) => {
    const dd: any = await getAccountInfo(dataUrl, {
      ...params,
      dbname: dbname,
      dataFieldA: ['Qty', 'Cost'],
      dataFieldB: ['inQty', 'inJE', 'outQty', 'outJE'],
    });

    if (dd.data?.length) {
      // tableData = ;
      const d = dd.data.map((a: any) => {
        return { ...a, xh: a.productCode };
      });
      dataSorce.current = d;
      if (!selectTreeNode) {
        setTtableData(d), console.log(dd.data, 'li w');
      } else {
        setTtableData(d?.filter((a: any) => a.typeID === selectTreeNode));
      }

      // 找出列字段
      let { baseUnitCode, productCode, productName, typeID, typeName, productID, ...rest } =
        dd.data[0];
      rest = Object.keys(rest).map((a: string) => a.split('_')[0]);
      // ;

      setColumnsData(
        tableColumnsData.concat([]).concat(buildCol([...new Set(rest)] as any, '') as []),
      );
      // setTransaction_Type(Transaction_Type.concat(dd.data.map((a: any) => a.mainType)));
    } else {
      setColumnsData(tableColumnsData);
      setTimeout(() => {
        setLoad(false); // 页面加载时间长
      }, 500);
    }
  };

  //
  const treeClickCallback = async ({ itemData }: any) => {
    if (itemData.name === '全部') {
      setTtableData(dataSorce.current);
      setSelectTreeNode(null);
    } else {
      setSelectTreeNode(itemData.id);
      setTtableData(dataSorce.current?.filter((a: any) => a.typeID === itemData.id));
    }
  };

  const refreshcallback = () => {
    if (ztDates?.length) {
      const q = searchRenderC.current.getFormSearchValues();
      const queryDate = {
        dates: q.dates,
        startYear: q.startYear,
        endYear: Number(q.endYear),
      };
      console.log(1, 'li', queryDate);

      let queyType: any = queryDate;
      if (q.TransactionType !== '全部') {
        queyType = { ...queyType, mainType: q.TransactionType };
      }

      getProductType(queyType);
    } else {
      notify('无筛选年度', 'error', 1000);
    }
  };

  useEffect((): void => {
    ztModel.refresh();
    getTransactionType();
  }, []);
  useEffect(() => {
    console.log(cpasNotesRef.current, 'li 11', searchRenderC.current);

    if (ztDates?.length) {
      getProductType({
        dates: [ztDates.at(-1)],
        startYear: ztDates.at(-1),
        endYear: Number(ztDates.at(-1)),
      });
    } else {
      notify('无筛选年度', 'error', 1000);
    }
  }, []);
  return (
    <div
      style={{
        border: '0px solid green',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {treeListData?.length && (
        <CpasLayout
          id="employee"
          ref={cpasNotesRef}
          height={'400px'}
          disabledHomeIcon={true}
          treeListData={treeListData}
          tableColumnsData={columnsData}
          tableData={tableData}
          renderSearch={renderSearch}
          searchClickCallback={searchcallback}
          // treeClickCallback={onTreeClickCallback}
          excelName={pageType}
          isLeftTree={true}
          refreshBtnCallback={refreshcallback}
          treeClickCallback={treeClickCallback}
          isJumpRowDetail={false}
        />
      )}
      <LoadPanel
        // shadingColor="rgba(0,0,0,0.4)"
        position={{ of: '#employee' }}
        // onHiding={hideLoadPanel}
        visible={Load}
        showIndicator={true}
        shading={true}
        showPane={true}
        // hideOnOutsideClick={hideOnOutsideClick}
      />
      <BusinessTypeModal dbname={dbname} ref={businessTypeModal} />
    </div>
  );
};

export default InventoryAnalysisProductStoreAnalysis;
